<?php
class EasyDate{
	
	public $delimeter = '-';
	public $format = 'Y-m-d';	
	public $timeshift = 0;
	public $onErrorReturnCurrentDate = true;
	
/*
 * change different short dates to appropriate pairs
 * empty -> today
 * +5 -> today+5
 * 16 -> 16th, this month
 * If $format is Y-m-d
 * 	12-16, 12/16 -> December 16, this year
 * 	9-12-16 -> 2009 December 16
 * @param string $date date to reformat
 * @param string $format to use
 * @param string $delimeter character delimeters year, month and day in return string
 * @param int $timeshift difference in hours between local time and server time
 * @return string reformatted date
 * @access public
*/	
	public function change($date = null){
		$this->format = str_replace('-', $this->delimeter, $this->format);
		
		if(!intval($date))	//not a number, return current date
			return($this->handleError());
		
		$d = '#';
		if($this->format == 'Y-m-d'){
			
			//if $date starts by a + sign than it menas today+x day
			if(substr($date,0,1) == '+')
				return(date('Y-m-d', mktime($this->timeshift, 0, 0, date("m"), date("d") + $date, date("Y"))));
			
			
			//all not numbers changed to $d
			$date = preg_replace('/\D/', $d, $date);
			
			$elvalasztok = substr_count($date, $d);
			switch($elvalasztok){
				case 0:
					$date = date('Y-m-d',mktime($this->timeshift, 0, 0, date("m"), $date, date("Y")));
					break;
				case 1:
					$date = explode($d, $date);
					$date = date('Y-m-d',mktime($this->timeshift, 0, 0, $date[0], $date[1], date("Y")));
					break;
				case 2:
					$date = explode($d, $date);
					$date = date('Y-m-d',mktime($this->timeshift, 0, 0, $date[1], $date[2], $date[0]));
					break;
				default:
					return $this->handleError();
				}
		
			//change $d to $this->delimeter
			$date = str_replace($d, $this->delimeter, $date);
		}
		return($date);
	}
	
/*
 * last day of the month
 * @param $month the month
 * @param $year the year
 * @return timestamp
 * @access private
*/
	public function lastday($year = '', $month = '') {
		if (empty($month)) {
		   $month = date('m');
		}
		if (empty($year)) {
		   $year = date('Y');
		}
		$result = strtotime("{$year}-{$month}-01");
		$result = strtotime('-1 second', strtotime('+1 month', $result));
		return $result;
	}
	
	private function handleError(){
		if($this->onErrorReturnCurrentDate){
			return date($this->format, mktime($this->timeshift, 0, 0, date("m"), date("d"), date("Y")));
		}
		else{
			return false;
		}
	}

}

?>
